<template>
  <j-modal
    title="审核领料单"
    :width="600"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item label="领料单号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input disabled v-decorator="['requisitionNo']" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="审核意见" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea placeholder="请输入审核意见" v-decorator="['approveComment']" :rows="4" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="上传附件" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-upload
                v-decorator="['attachments']"
                :file-upload-url="uploadUrl"
                :text="'上传附件'"
                :number="5"
                :token="token"
                :data="uploadParams"
                @change="handleAttachmentChange"
              ></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import { FormMixin } from '@/mixins/formMixin'
import { postAction } from '@/api/manage'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import JUpload from '@/components/jeecg/JUpload'
import Vue from 'vue'

export default {
  name: 'RequisitionApproveModal',
  mixins: [FormMixin],
  components: {
    JUpload,
  },
  data() {
    return {
      form: null,
      title: '审核领料单',
      visible: false,
      model: {},
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
      confirmLoading: false,
      url: {
        approve: '/wms/requisition/approve',
      },
      uploadUrl: window._CONFIG['domianURL'] + '/wms/requisition/attachment/upload',
      token: '',
      attachments: [],
      uploadParams: {},
    }
  },
  created() {
    this.token = Vue.ls.get(ACCESS_TOKEN)
  },
  mounted() {
    this.form = this.$form.createForm(this)
  },
  methods: {
    show(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true

      // 设置上传参数
      this.uploadParams = {
        requisitionId: record.id,
        token: this.token,
      }

      // 设置表单初始值
      this.$nextTick(() => {
        this.form.setFieldsValue({
          requisitionNo: this.model.requisitionNo,
          approveComment: '',
          attachments: '', // 初始化附件字段为空字符串
        })
      })

      console.log('初始化模态框 - 表单已重置')
    },

    close() {
      this.visible = false
    },

    handleOk() {
      const that = this

      // 表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true

          console.log('表单验证通过 - values:', values)

          // 处理附件格式，将字符串转换为List<Map<String,String>>
          let attachmentList = []

          // 从表单中获取附件值
          const attachmentsValue = values.attachments
          console.log('从表单获取的附件值:', attachmentsValue)

          // 如果是字符串（逗号分隔的文件路径），将其转换为数组
          if (typeof attachmentsValue === 'string' && attachmentsValue) {
            const paths = attachmentsValue.split(',')
            console.log('附件路径数组:', paths)

            paths.forEach((path, index) => {
              if (path) {
                const fileName = path.substring(path.lastIndexOf('/') + 1)
                const fileType = this.getFileExtension(fileName)

                attachmentList.push({
                  fileName: fileName,
                  filePath: path,
                  fileType: fileType,
                })
                console.log(`附件[${index}] - 从路径构建:`, fileName, path, fileType)
              }
            })
          }

          console.log('处理后的附件列表:', attachmentList)

          // 构建提交数据
          let formData = {
            id: this.model.id,
            approveComment: values.approveComment || '',
            attachments: attachmentList,
          }

          console.log('提交审核数据:', formData)

          // 发送请求
          postAction(this.url.approve, formData)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                that.close()
              } else {
                that.$message.warning(res.message || '操作失败')
              }
            })
            .catch((error) => {
              console.error('审核请求失败:', error)
              that.$message.error('审核请求失败，请检查网络或联系管理员')
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },

    // 获取文件扩展名
    getFileExtension(filename) {
      if (!filename) return ''
      return filename.slice(((filename.lastIndexOf('.') - 1) >>> 0) + 2).toLowerCase()
    },

    // 处理附件变更
    handleAttachmentChange(fileList) {
      console.log('附件变更 - 文件列表:', fileList)
    },
  },
}
</script>

<style scoped>
</style> 